<template>
  <div class="user-address">
    <el-card class="address-card">
      <template #header>
        <div class="card-header">
          <h3>收货地址管理</h3>
          <el-button type="primary" @click="handleAddAddress">
            新增收货地址
          </el-button>
        </div>
      </template>

      <div class="address-list" v-loading="loading">
        <el-empty v-if="!addressList.length" description="暂无收货地址" />
        
        <div v-else class="address-grid">
          <el-card 
            v-for="address in addressList" 
            :key="address.id" 
            class="address-item"
            :class="{ 'is-default': address.isDefault }"
          >
            <div class="address-info">
              <div class="recipient-info">
                <span class="name">{{ address.recipientName }}</span>
                <span class="phone">{{ address.telephone }}</span>
                <el-tag v-if="address.isDefault" size="small" type="success">默认</el-tag>
              </div>
              <div class="address-detail">
                {{ formatAddress(address) }}
              </div>
            </div>
            <div class="address-actions">
              <el-button 
                v-if="!address.isDefault" 
                type="primary" 
                link
                @click="handleSetDefault(address)"
              >
                设为默认
              </el-button>
              <el-button type="primary" link @click="handleEdit(address)">
                编辑
              </el-button>
              <el-button 
                type="danger" 
                link 
                @click="handleDelete(address)"
                :disabled="address.isDefault"
              >
                删除
              </el-button>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>

    <!-- 地址编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑收货地址' : '新增收货地址'"
      width="500px"
    >
      <el-form
        ref="addressFormRef"
        :model="addressForm"
        :rules="addressRules"
        label-width="100px"
      >
        <el-form-item label="收货人" prop="recipientName">
          <el-input v-model="addressForm.recipientName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="telephone">
          <el-input v-model="addressForm.telephone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="addressForm.region"
            :options="regionOptions"
            placeholder="请选择所在地区"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="addressDetail">
          <el-input
            v-model="addressForm.addressDetail"
            type="textarea"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认收货地址</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAddressList, createAddress, updateAddress, deleteAddress } from '@/api/address'

// 状态数据
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const addressList = ref([])
const addressFormRef = ref(null)

// 从cookie获取uid - 移到前面
const getUserId = () => {
  const cookies = document.cookie.split(';')
  for (let cookie of cookies) {
    const [name, value] = cookie.trim().split('=')
    if (name === 'id') {
      return value
    }
  }
  return null
}

// 表单数据
const addressForm = reactive({
  id: '',
  uid: getUserId(), // 现在可以正常调用了
  recipientName: '',
  telephone: '',
  province: '',
  city: '',
  district: '',
  addressDetail: '',
  postalCode: '',
  isDefault: false
})

// 新增地址
const handleAddAddress = () => {
  isEdit.value = false
  dialogVisible.value = true
  addressForm.id = ''
  addressForm.uid = getUserId()
  addressForm.recipientName = ''
  addressForm.telephone = ''
  addressForm.province = ''
  addressForm.city = ''
  addressForm.district = ''
  addressForm.addressDetail = ''
  addressForm.postalCode = ''
  addressForm.isDefault = false
  addressForm.region = []  // 添加这行，重置 region 字段
}

// 提交表单
const handleSubmit = async () => {
  if (!addressFormRef.value) return
  
  await addressFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 在提交前处理地区数据
        const [province, city, district] = addressForm.region || []
        
        // 处理直辖市的特殊情况
        let finalProvince = province
        let finalCity = city
        let finalDistrict = district
        
        // 判断是否是直辖市（北京、天津、上海、重庆）
        if (['11', '12', '31', '50'].includes(province)) {
          finalProvince = province
          finalCity = province + '01'  // 直辖市的市级代码通常是省级代码+'01'
          finalDistrict = city  // 直辖市的第二级实际上是区县级
        }
        
        // 获取区县代码作为邮政编码的基础，不足6位补0
        const postalCode = (finalDistrict || '').padEnd(6, '0')
        
        // 获取省市区的文字描述
        const provinceText = regionOptions.value.find(p => p.value === finalProvince)?.label || ''
        const cityText = regionOptions.value
          .find(p => p.value === finalProvince)
          ?.children?.find(c => c.value === finalCity)?.label || ''
        const districtText = regionOptions.value
          .find(p => p.value === finalProvince)
          ?.children?.find(c => c.value === finalCity)
          ?.children?.find(d => d.value === finalDistrict)?.label || ''

        const submitData = {
          ...addressForm,
          province: provinceText,  // 使用文字描述
          city: cityText,         // 使用文字描述
          district: districtText, // 使用文字描述
          postalCode,            // 保持使用编码
          default: addressForm.isDefault
        }
        delete submitData.region
        delete submitData.isDefault

        console.log('提交的地址数据：', submitData)

        const api = isEdit.value ? updateAddress : createAddress
        const res = await api(submitData)
        ElMessage.success(`${isEdit.value ? '修改' : '添加'}地址成功`)
        dialogVisible.value = false
        fetchAddressList()
      } catch (error) {
        ElMessage.error(`${isEdit.value ? '修改' : '添加'}地址失败，请重试`)
      }
    }
  })
}

// 表单校验规则
const addressRules = {
  recipientName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  telephone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  addressDetail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在 5 到 100 个字符', trigger: 'blur' }
  ]
}

// 获取地址列表
// 获取地址列表
const fetchAddressList = async () => {
  loading.value = true
  try {
    const res = await getAddressList()
    // 处理响应数据，将default字段映射为isDefault
    if (res && Array.isArray(res)) {
      addressList.value = res.map(address => ({
        ...address,
        isDefault: address.default, // 将default映射为isDefault
        region: [address.province, address.city, address.district] // 添加region字段用于显示
      }))
    } else {
      addressList.value = []
    }
  } catch (error) {
    console.error('获取地址列表失败：', error)
    ElMessage.error('获取地址列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化地址
const formatAddress = (address) => {
  // 使用省市区代码获取对应的文本（这里假设你有一个方法来转换代码到文本）
  const regionText = address.region.map(code => {
    const option = regionOptions.value.find(item => item.value === code)
    return option ? option.label : code
  }).join(' ')
  return `${regionText} ${address.addressDetail}`
}

// 编辑地址
const handleEdit = (address) => {
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(addressForm, {
    ...address,
    uid: getUserId(), // 确保编辑时也设置userId
    region: [address.province, address.city, address.district], // 添加region字段
    isDefault: address.default // 使用后端的default字段
  })
}

// 设为默认地址
const handleSetDefault = async (address) => {
  try {
    const res = await updateAddress({
      ...address,
      uid: getUserId(), // 添加 uid
      default: true  // 使用 default 而不是 isDefault，因为后端使用的是 default
    })
    ElMessage.success('设置默认地址成功')
    // 重新获取最新的地址列表
    await fetchAddressList()
  } catch (error) {
    console.error('设置默认地址失败：', error)
    ElMessage.error('设置默认地址失败，请重试')
  }
}

// 删除地址
const handleDelete = (address) => {
  ElMessageBox.confirm('确定要删除该收货地址吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAddress(address.id)
      ElMessage.success('删除地址成功')
      fetchAddressList()  // 这里也需要修改
    } catch (error) {
      ElMessage.error('删除地址失败，请重试')
    }
  })
}



// 初始化
onMounted(() => {
  fetchAddressList()  // 这里也需要修改
})

// 导入地区数据和转换函数
import regionData from '/public/data/pca-code.json'
import { transformRegionData } from '@/utils/region'

// 地区数据 - 转换为级联选择器格式
const regionOptions = ref(transformRegionData(regionData))

// 移除不需要的fetchRegionData方法和相关的onMounted调用
onMounted(() => {
  fetchAddressList()
})
</script>

<style scoped>
.user-address {
  width: 100%;
}

.address-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.address-grid {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
}

.address-item {
  position: relative;
  transition: all 0.3s;
}

.address-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.address-item.is-default {
  border: 1px solid var(--el-color-success);
}

.recipient-info {
  margin-bottom: 10px;
}

.name {
  font-size: 16px;
  font-weight: bold;
  margin-right: 10px;
}

.phone {
  color: var(--el-text-color-secondary);
  margin-right: 10px;
}

.address-detail {
  color: var(--el-text-color-regular);
  line-height: 1.5;
  margin-bottom: 15px;
}

.address-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 10px;
  margin-top: 10px;
}

:deep(.el-cascader) {
  width: 100%;
}
</style>